package org.zebra.satoken.security;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.hutool.extra.spring.SpringUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.zebra.common.util.UriWhiteUtil;
import org.zebra.satoken.LoginHelper;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * 权限安全配置
 *
 * @author zhanghongbin
 */
@Configuration
@Import({AllUrlHandler.class})
@ConditionalOnProperty(name = "zebra.satoken.security.enabled", havingValue = "true")
@EnableConfigurationProperties(SecurityProperties.class)
@RequiredArgsConstructor
public class SecurityConfig implements WebMvcConfigurer {

    private final SecurityProperties securityProperties;

    @Autowired(required = false)
    private SaInterceptor saInterceptor;

    /**
     * 注册sa-token的拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        if (saInterceptor == null) {
            saInterceptor = new SecuritySaInterceptor();
        }
        saInterceptor.setAuth(handler -> {
            AllUrlHandler allUrlHandler = SpringUtil.getBean(AllUrlHandler.class);
            SaRouter.match(allUrlHandler.getUrls())
                    // 对未排除的路径进行检查
                    .check(() -> {
                        LoginHelper.getLoginUser();
                        SpringUtil.getApplicationContext().publishEvent(AccessType.HTTP);
                    });
        });

        // 注册路由拦截器，自定义验证规则
        Set<String> whiteSet = new HashSet<>(UriWhiteUtil.getDefaultUriWhite());
        whiteSet.addAll(Arrays.asList(securityProperties.getExcludes()));
        registry.addInterceptor(saInterceptor)
                .addPathPatterns("/**")
                // 排除不需要拦截的路径
                .excludePathPatterns(whiteSet.toArray(String[]::new));
    }

    //    @ConditionalOnBean(ForestConfigurationProperties.class)
    //    @Configuration
    //    static class Forest {
    //        public Forest(ForestConfigurationProperties forestConfigurationProperties) {
    //            forestConfigurationProperties.getInterceptors().add(ForestContextTokenInterceptor.class);
    //        }
    //    }
}
